using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using WeMakeSP.Platform.SharePoint.Administration;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace WeMakeSP.SiteManagement.Features
{
    public class SiteManagementFeatureEventReceiver : SPFeatureReceiver
    {
        #region Fields

        /// <summary>
        /// The feature activation timestamp.
        /// </summary>
        private DateTime featureActivationDateTime;

        /// <summary>
        /// Holds error message of the feature activation.
        /// </summary>
        private List<string> featureActivationErrors = new List<string>();

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the Microsoft.SharePoint.SPFeatureReceiver class.
        /// </summary>
        public SiteManagementFeatureEventReceiver()
        {
        }

        #endregion

        #region Public Override Methods

        /// <summary>
        /// Occurs after a Feature is installed.
        /// </summary>
        /// <param name="properties">A Microsoft.SharePoint.SPFeatureReceiverProperties object that represents properties of the event handler.</param>
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        /// <summary>
        /// Occurs after a Feature is activated.
        /// </summary>
        /// <param name="properties">A Microsoft.SharePoint.SPFeatureReceiverProperties object that represents properties of the event handler.</param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site =
                properties.Feature.Parent as SPSite;

            SPWebApplication webApplication =
                site.WebApplication;

            string featureName =
                properties.Feature.Definition.DisplayName;

            this.featureActivationDateTime = DateTime.Now;
            
            // Impersonate as the AppPool account of the web application.

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // Breadcrumb.

                try
                {
                    UpdateLayoutSiteMap uls =
                    new UpdateLayoutSiteMap(webApplication);

                    uls.AddEntry("Subsites customization", "/_layouts/SiteManagement/sitehierarchy.aspx", "/_layouts/settings.aspx");
                    uls.SubmitJob();
                }
                catch (UnauthorizedAccessException ex)
                {
                    this.featureActivationErrors.Add("Failed to start the job which add the entry in the site map. The error was caused by insuficient privileges. \n" + ex);
                }
                catch (Exception ex)
                {
                    this.featureActivationErrors.Add(ex.Message);
                }

                // Resources.            

                try
                {
                    foreach (KeyValuePair<SPUrlZone, SPIisSettings> iisSettings in webApplication.IisSettings)
                    {
                        string sourcePath =
                            string.Format(@"{0}\FEATURES\{1}\Resources\", SPUtility.GetGenericSetupPath("Template"), featureName);

                        string destPath = Path.Combine(iisSettings.Value.Path.ToString(), "App_GlobalResources");

                        string[] filePaths = Directory.GetFiles(sourcePath, "*.resx");

                        // Copy the files.

                        foreach (string filePath in filePaths)
                        {

                            string fileName = Path.GetFileName(filePath);

                            File.Copy(filePath, Path.Combine(destPath, fileName), true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.featureActivationErrors.Add(ex.Message);
                }
                
            });            
        }

        /// <summary>
        /// Occurs when a Feature is deactivated.
        /// </summary>
        /// <param name="properties">A Microsoft.SharePoint.SPFeatureReceiverProperties object that represents properties of the event handler.</param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
        }

        /// <summary>
        /// Occurs when a Feature is uninstalled.
        /// </summary>
        /// <param name="properties">A Microsoft.SharePoint.SPFeatureReceiverProperties object that represents properties of the event handler.</param>
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

        #endregion

    }
}
